<template>
  <div class="stock-warning-page">
    <!-- 页面标题 -->
    <h2 class="page-title mb-4">库存预警管理</h2>
    
    <!-- 库存预警查询表单 -->
    <el-card shadow="hover" class="mb-4">
      <el-form :model="searchForm" inline class="demo-form-inline">
        <el-form-item label="货品">
          <el-input v-model="searchForm.goodsName" placeholder="请输入货品名称/编号" style="width: 200px;" />
        </el-form-item>
        <el-form-item label="货品类型">
          <el-select v-model="searchForm.goodsType" placeholder="请选择">
            <el-option label="全部" value="" />
            <el-option label="电子产品" value="electronics" />
            <el-option label="家电" value="appliance" />
            <el-option label="服装" value="clothing" />
            <el-option label="食品" value="food" />
            <el-option label="化妆品" value="cosmetics" />
            <el-option label="饮品" value="drink" />
            <el-option label="家居用品" value="home" />
            <el-option label="办公用品" value="office" />
          </el-select>
        </el-form-item>
        <el-form-item label="上下限">
          <el-select v-model="searchForm.limitType" placeholder="请选择">
            <el-option label="全部" value="" />
            <el-option label="低于下限" value="below" />
            <el-option label="高于上限" value="above" />
          </el-select>
        </el-form-item>
        <el-form-item label="当前库存">
          <el-input v-model.number="searchForm.currentStockMin" placeholder="最小值" style="width: 100px; margin-right: 5px;" />
          <span class="mx-2">-</span>
          <el-input v-model.number="searchForm.currentStockMax" placeholder="最大值" style="width: 100px;" />
        </el-form-item>
        <el-form-item>
          <el-button type="default" @click="handleReset">重置</el-button>
          <el-button type="primary" @click="handleSearch">查询</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮和统计信息 -->
    <div class="flex mb-4 justify-between items-center">
      <div>
        <el-button type="success" @click="handleExport" icon="DocumentCopy">导出</el-button>
        <el-button type="info" @click="handleRefresh" icon="Refresh">刷新</el-button>
        <el-button type="warning" @click="handleBatchSetLimit" icon="Setting">批量设置上下限</el-button>
      </div>
      <div class="stats-info">
        <el-tag type="danger" size="small" class="mr-2">低于下限: {{ belowCount }} 个</el-tag>
        <el-tag type="warning" size="small">高于上限: {{ aboveCount }} 个</el-tag>
      </div>
    </div>

    <!-- 库存预警表格 -->
    <el-card shadow="hover">
      <div class="table-header mb-4">
        <span class="table-title">库存预警列表</span>
        <span class="data-count">共 {{ pagination.total }} 条预警记录</span>
      </div>
      <el-table 
        :data="tableData" 
        border 
        style="width: 100%" 
        stripe 
        highlight-current-row 
        row-class-name="warning-row"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="index" label="序号" width="80" align="center" />
        <el-table-column prop="goodsCode" label="货品编号" width="120" align="center" />
        <el-table-column prop="goodsName" label="货品名称" width="180">
          <template #default="scope">
            <span class="goods-name">{{ scope.row.goodsName }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="spec" label="规格型号" width="120" align="center" />
        <el-table-column prop="unit" label="单位" width="80" align="center" />
        <el-table-column prop="goodsType" label="货品类型" width="120" align="center">
          <template #default="scope">
            <el-tag :type="getTypeTagType(scope.row.goodsType)">
              {{ getTypeLabel(scope.row.goodsType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="currentStock" label="当前库存" width="120" align="center">
          <template #default="scope">
            <span :class="getStockClass(scope.row)">
              {{ scope.row.currentStock }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="stockLower" label="库存下限" width="120" align="center" />
        <el-table-column prop="stockUpper" label="库存上限" width="120" align="center" />
        <el-table-column label="预警状态" width="120" align="center">
          <template #default="scope">
            <el-tag :type="getWarningTagType(scope.row)">
              {{ getWarningStatus(scope.row) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="预警百分比" width="120" align="center">
          <template #default="scope">
            <el-progress 
              :percentage="getWarningPercentage(scope.row)" 
              :color="getProgressColor(scope.row)"
              :stroke-width="12"
              :show-text="true"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" align="center">
          <template #default="scope">
            <el-button type="primary" size="small" @click="handleViewDetails(scope.row)">查看详情</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total"
        class="mt-4"
      />
    </el-card>
    
    <!-- 库存预警详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      :title="currentData ? `${currentData.goodsName} - 库存预警详情` : '库存预警详情'"
      width="80%"
      :close-on-click-modal="false"
    >
      <template v-if="currentData">
        <!-- 基本信息 -->
        <el-card shadow="hover" class="mb-4">
          <h3 class="card-title mb-3">基本信息</h3>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="货品编号">{{ currentData.goodsCode }}</el-descriptions-item>
            <el-descriptions-item label="货品名称">{{ currentData.goodsName }}</el-descriptions-item>
            <el-descriptions-item label="规格型号">{{ currentData.spec }}</el-descriptions-item>
            <el-descriptions-item label="单位">{{ currentData.unit }}</el-descriptions-item>
            <el-descriptions-item label="货品类型">
              <el-tag :type="getTypeTagType(currentData.goodsType)">
                {{ getTypeLabel(currentData.goodsType) }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="预警状态">
              <el-tag :type="getWarningTagType(currentData)">
                {{ getWarningStatus(currentData) }}
              </el-tag>
            </el-descriptions-item>
          </el-descriptions>
        </el-card>
        
        <!-- 库存信息 -->
        <el-card shadow="hover" class="mb-4">
          <h3 class="card-title mb-3">库存信息</h3>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="当前库存">
              <span :class="getStockClass(currentData)" style="font-size: 18px; font-weight: 600;">
                {{ currentData.currentStock }}
              </span>
            </el-descriptions-item>
            <el-descriptions-item label="库存下限">
              <span style="color: #f56c6c; font-weight: 500;">{{ currentData.stockLower }}</span>
            </el-descriptions-item>
            <el-descriptions-item label="库存上限">
              <span style="color: #e6a23c; font-weight: 500;">{{ currentData.stockUpper }}</span>
            </el-descriptions-item>
            <el-descriptions-item label="预警百分比">
              <el-progress 
                :percentage="getWarningPercentage(currentData)" 
                :color="getProgressColor(currentData)"
                :stroke-width="16"
                :show-text="true"
                class="progress-large"
              />
            </el-descriptions-item>
            <el-descriptions-item label="建议操作" :span="2">
              <el-tag type="info" v-if="currentData.warningType === 'below'">
                建议立即补货，当前库存已低于安全库存线！
              </el-tag>
              <el-tag type="warning" v-else-if="currentData.warningType === 'above'">
                建议减少采购，当前库存已超过上限！
              </el-tag>
            </el-descriptions-item>
          </el-descriptions>
        </el-card>
        
        <!-- 历史库存趋势 -->
        <el-card shadow="hover">
          <h3 class="card-title mb-3">历史库存趋势</h3>
          <div class="trend-chart" style="height: 300px; background-color: #fafafa; border-radius: 4px; display: flex; align-items: center; justify-content: center;">
            <div class="trend-placeholder">
              <el-icon class="el-icon--large"><DataLine /></el-icon>
              <p style="margin-top: 10px; color: #909399;">历史库存趋势图表</p>
              <p style="color: #c0c4cc; font-size: 12px;">（最近30天的库存变化）</p>
            </div>
          </div>
          
          <!-- 近期库存变动记录 -->
          <div class="recent-changes mt-4">
            <h4 class="section-title">近期库存变动记录</h4>
            <el-table :data="currentData.recentChanges" border style="width: 100%;" size="small">
              <el-table-column prop="date" label="日期" width="120" />
              <el-table-column prop="time" label="时间" width="100" />
              <el-table-column prop="operation" label="操作类型" width="100">
                <template #default="scope">
                  <el-tag :type="getOperationTagType(scope.row.operation)">
                    {{ scope.row.operation }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="quantity" label="数量" width="100" align="center">
                <template #default="scope">
                  <span :class="{ 'text-green': scope.row.quantity > 0, 'text-red': scope.row.quantity < 0 }">
                    {{ scope.row.quantity > 0 ? '+' : '' }}{{ scope.row.quantity }}
                  </span>
                </template>
              </el-table-column>
              <el-table-column prop="afterStock" label="变动后库存" width="120" align="center" />
              <el-table-column prop="operator" label="操作员" width="100" />
              <el-table-column prop="remark" label="备注" />
            </el-table>
          </div>
        </el-card>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue';
import { ElLoading, ElMessage } from 'element-plus';
import { DataLine } from '@element-plus/icons-vue';

// 查询表单数据（硬编码，无API依赖）
const searchForm = reactive({
  goodsName: '',
  goodsType: '',
  limitType: '',
  currentStockMin: '',
  currentStockMax: '',
});

// 完整的库存预警数据（硬编码，更丰富的数据）
const fullWarningData = ref([
  {
    index: 1,
    goodsCode: 'HW1001',
    goodsName: 'Apple iPhone 15 Pro',
    spec: '256GB/钛金属原色',
    unit: '台',
    goodsType: 'electronics',
    currentStock: 8,
    stockLower: 20,
    stockUpper: 100,
    warningType: 'below',
    warningPercentage: 60,
    recentChanges: generateRecentChanges(8, 'below')
  },
  {
    index: 2,
    goodsCode: 'HW1002',
    goodsName: '三星QLED 8K智能电视',
    spec: '85英寸/QN900C',
    unit: '台',
    goodsType: 'appliance',
    currentStock: 150,
    stockLower: 10,
    stockUpper: 50,
    warningType: 'above',
    warningPercentage: 200,
    recentChanges: generateRecentChanges(150, 'above')
  },
  {
    index: 3,
    goodsCode: 'HW1003',
    goodsName: '耐克Air Jordan 1',
    spec: '芝加哥/42码',
    unit: '双',
    goodsType: 'clothing',
    currentStock: 3,
    stockLower: 15,
    stockUpper: 80,
    warningType: 'below',
    warningPercentage: 80,
    recentChanges: generateRecentChanges(3, 'below')
  },
  {
    index: 4,
    goodsCode: 'HW1004',
    goodsName: '可口可乐',
    spec: '600ml/瓶',
    unit: '箱',
    goodsType: 'drink',
    currentStock: 350,
    stockLower: 50,
    stockUpper: 200,
    warningType: 'above',
    warningPercentage: 75,
    recentChanges: generateRecentChanges(350, 'above')
  },
  {
    index: 5,
    goodsCode: 'HW1005',
    goodsName: '戴森空气净化器',
    spec: 'TP09/黑金版',
    unit: '台',
    goodsType: 'appliance',
    currentStock: 6,
    stockLower: 15,
    stockUpper: 60,
    warningType: 'below',
    warningPercentage: 60,
    recentChanges: generateRecentChanges(6, 'below')
  },
  {
    index: 6,
    goodsCode: 'HW1006',
    goodsName: '兰蔻小黑瓶精华液',
    spec: '50ml',
    unit: '瓶',
    goodsType: 'cosmetics',
    currentStock: 2,
    stockLower: 25,
    stockUpper: 120,
    warningType: 'below',
    warningPercentage: 92,
    recentChanges: generateRecentChanges(2, 'below')
  },
  {
    index: 7,
    goodsCode: 'HW1007',
    goodsName: '双立人厨具套装',
    spec: 'TWIN Chef 32件套',
    unit: '套',
    goodsType: 'home',
    currentStock: 180,
    stockLower: 30,
    stockUpper: 100,
    warningType: 'above',
    warningPercentage: 80,
    recentChanges: generateRecentChanges(180, 'above')
  },
  {
    index: 8,
    goodsCode: 'HW1008',
    goodsName: '乐高星球大战系列',
    spec: '75331/执行者号',
    unit: '盒',
    goodsType: 'home',
    currentStock: 45,
    stockLower: 20,
    stockUpper: 40,
    warningType: 'above',
    warningPercentage: 12.5,
    recentChanges: generateRecentChanges(45, 'above')
  },
  {
    index: 9,
    goodsCode: 'HW1009',
    goodsName: '星巴克咖啡豆',
    spec: '500g/袋',
    unit: '袋',
    goodsType: 'food',
    currentStock: 12,
    stockLower: 40,
    stockUpper: 150,
    warningType: 'below',
    warningPercentage: 70,
    recentChanges: generateRecentChanges(12, 'below')
  },
  {
    index: 10,
    goodsCode: 'HW1010',
    goodsName: 'HP LaserJet Pro打印机',
    spec: 'M428fdw/黑白激光',
    unit: '台',
    goodsType: 'office',
    currentStock: 0,
    stockLower: 10,
    stockUpper: 50,
    warningType: 'below',
    warningPercentage: 100,
    recentChanges: generateRecentChanges(0, 'below')
  },
  {
    index: 11,
    goodsCode: 'HW1011',
    goodsName: '华为MateBook X Pro',
    spec: 'i9/32GB/2TB/灰',
    unit: '台',
    goodsType: 'electronics',
    currentStock: 5,
    stockLower: 15,
    stockUpper: 70,
    warningType: 'below',
    warningPercentage: 66.7,
    recentChanges: generateRecentChanges(5, 'below')
  },
  {
    index: 12,
    goodsCode: 'HW1012',
    goodsName: '美的变频空调',
    spec: 'KFR-35GW/1.5匹',
    unit: '台',
    goodsType: 'appliance',
    currentStock: 95,
    stockLower: 20,
    stockUpper: 50,
    warningType: 'above',
    warningPercentage: 90,
    recentChanges: generateRecentChanges(95, 'above')
  },
  {
    index: 13,
    goodsCode: 'HW1013',
    goodsName: 'Adidas Ultraboost跑鞋',
    spec: '22款/43码',
    unit: '双',
    goodsType: 'clothing',
    currentStock: 8,
    stockLower: 25,
    stockUpper: 100,
    warningType: 'below',
    warningPercentage: 68,
    recentChanges: generateRecentChanges(8, 'below')
  },
  {
    index: 14,
    goodsCode: 'HW1014',
    goodsName: '三只松鼠坚果礼盒',
    spec: '1.5kg/盒',
    unit: '盒',
    goodsType: 'food',
    currentStock: 220,
    stockLower: 50,
    stockUpper: 150,
    warningType: 'above',
    warningPercentage: 46.7,
    recentChanges: generateRecentChanges(220, 'above')
  },
  {
    index: 15,
    goodsCode: 'HW1015',
    goodsName: 'SK-II神仙水',
    spec: '230ml',
    unit: '瓶',
    goodsType: 'cosmetics',
    currentStock: 3,
    stockLower: 20,
    stockUpper: 80,
    warningType: 'below',
    warningPercentage: 85,
    recentChanges: generateRecentChanges(3, 'below')
  },
  {
    index: 16,
    goodsCode: 'HW1016',
    goodsName: '百事可乐',
    spec: '500ml/瓶',
    unit: '箱',
    goodsType: 'drink',
    currentStock: 180,
    stockLower: 60,
    stockUpper: 120,
    warningType: 'above',
    warningPercentage: 50,
    recentChanges: generateRecentChanges(180, 'above')
  },
  {
    index: 17,
    goodsCode: 'HW1017',
    goodsName: '宜家BILLY书柜',
    spec: '202x80cm/白色',
    unit: '个',
    goodsType: 'home',
    currentStock: 45,
    stockLower: 10,
    stockUpper: 30,
    warningType: 'above',
    warningPercentage: 50,
    recentChanges: generateRecentChanges(45, 'above')
  },
  {
    index: 18,
    goodsCode: 'HW1018',
    goodsName: '得力A4打印纸',
    spec: '80g/500张/包',
    unit: '包',
    goodsType: 'office',
    currentStock: 5,
    stockLower: 50,
    stockUpper: 200,
    warningType: 'below',
    warningPercentage: 90,
    recentChanges: generateRecentChanges(5, 'below')
  },
  {
    index: 19,
    goodsCode: 'HW1019',
    goodsName: '索尼PlayStation 5',
    spec: '光驱版',
    unit: '台',
    goodsType: 'electronics',
    currentStock: 2,
    stockLower: 15,
    stockUpper: 60,
    warningType: 'below',
    warningPercentage: 86.7,
    recentChanges: generateRecentChanges(2, 'below')
  },
  {
    index: 20,
    goodsCode: 'HW1020',
    goodsName: '海尔全自动洗衣机',
    spec: 'XQG100-BD14126L/10kg',
    unit: '台',
    goodsType: 'appliance',
    currentStock: 65,
    stockLower: 15,
    stockUpper: 40,
    warningType: 'above',
    warningPercentage: 62.5,
    recentChanges: generateRecentChanges(65, 'above')
  }
]);

// 分页参数 - 提前定义以避免初始化顺序问题
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0,
});

// 表格数据（根据分页和筛选条件动态更新）
const tableData = ref([]);

// 筛选后的数据
const filteredData = ref([]);

// 详情对话框
const detailDialogVisible = ref(false);
const currentData = ref(null);

// 生成近期库存变动记录
function generateRecentChanges(currentStock, warningType) {
  const operations = ['入库', '出库', '盘点', '调拨'];
  const operators = ['张三', '李四', '王五', '赵六', '钱七'];
  const changes = [];
  let stock = currentStock;
  
  // 生成10条变动记录，按时间倒序
  for (let i = 0; i < 10; i++) {
    const date = new Date();
    date.setDate(date.getDate() - i - Math.floor(Math.random() * 20));
    
    const operation = operations[Math.floor(Math.random() * operations.length)];
    let quantity;
    
    // 根据预警类型调整数量生成逻辑
    if (warningType === 'below') {
      // 低于下限的，最近应该多是出库操作
      if (operation === '入库') {
        quantity = Math.floor(Math.random() * 20) + 5;
      } else {
        quantity = -(Math.floor(Math.random() * 10) + 1);
      }
    } else {
      // 高于上限的，最近应该多是入库操作
      if (operation === '出库') {
        quantity = -(Math.floor(Math.random() * 20) + 5);
      } else {
        quantity = Math.floor(Math.random() * 10) + 1;
      }
    }
    
    // 更新库存
    const afterStock = stock + quantity;
    
    changes.push({
      date: date.toLocaleDateString(),
      time: `${Math.floor(Math.random() * 24)}:${String(Math.floor(Math.random() * 60)).padStart(2, '0')}:${String(Math.floor(Math.random() * 60)).padStart(2, '0')}`,
      operation,
      quantity,
      afterStock: Math.max(0, afterStock),
      operator: operators[Math.floor(Math.random() * operators.length)],
      remark: `${operation}操作备注`
    });
    
    stock = afterStock;
  }
  
  return changes.reverse();
}

// 更新分页数据
const updatePagedData = () => {
  const start = (pagination.currentPage - 1) * pagination.pageSize;
  const end = start + pagination.pageSize;
  tableData.value = filteredData.value.slice(start, end).map((item, index) => ({
    ...item,
    index: start + index + 1
  }));
  pagination.total = filteredData.value.length;
};

// 初始化数据
const initData = () => {
  // 复制完整数据以避免直接修改原始数据
  filteredData.value = JSON.parse(JSON.stringify(fullWarningData.value));
  updatePagedData();
};

// 初始化时加载数据
initData();

// 计算属性：低于下限的数量
const belowCount = computed(() => {
  return filteredData.value.filter(item => item.warningType === 'below').length;
});

// 计算属性：高于上限的数量
const aboveCount = computed(() => {
  return filteredData.value.filter(item => item.warningType === 'above').length;
});

// 获取操作类型标签颜色
const getOperationTagType = (operation) => {
  const typeMap = {
    '入库': 'success',
    '出库': 'danger',
    '盘点': 'warning',
    '调拨': 'primary'
  };
  return typeMap[operation] || 'default';
};

// 获取类型标签颜色
const getTypeTagType = (type) => {
  const typeMap = {
    'electronics': 'primary',
    'appliance': 'success',
    'clothing': 'warning',
    'food': 'danger',
    'cosmetics': 'info',
    'drink': 'success',
    'home': 'warning',
    'office': 'primary'
  };
  return typeMap[type] || 'default';
};

// 获取类型标签
const getTypeLabel = (type) => {
  const typeMap = {
    'electronics': '电子产品',
    'appliance': '家电',
    'clothing': '服装',
    'food': '食品',
    'cosmetics': '化妆品',
    'drink': '饮品',
    'home': '家居用品',
    'office': '办公用品'
  };
  return typeMap[type] || type;
};

// 获取库存样式类名
const getStockClass = (row) => {
  if (row.warningType === 'below') {
    return 'stock-below';
  } else if (row.warningType === 'above') {
    return 'stock-above';
  }
  return '';
};

// 获取预警标签类型
const getWarningTagType = (row) => {
  if (row.warningType === 'below') {
    return 'danger';
  } else if (row.warningType === 'above') {
    return 'warning';
  }
  return 'success';
};

// 获取预警状态文本
const getWarningStatus = (row) => {
  if (row.warningType === 'below') {
    return '低于下限';
  } else if (row.warningType === 'above') {
    return '高于上限';
  }
  return '正常';
};

// 获取预警百分比
const getWarningPercentage = (row) => {
  return row.warningPercentage;
};

// 获取进度条颜色
const getProgressColor = (row) => {
  if (row.warningType === 'below') {
    return '#f56c6c'; // 红色
  } else if (row.warningType === 'above') {
    return '#e6a23c'; // 黄色
  }
  return '#67c23a'; // 绿色
};

// 分页参数已提前定义，避免初始化顺序问题

// 应用筛选条件
const applyFilters = () => {
  // 重置到第一页
  pagination.currentPage = 1;
  
  // 从完整数据开始筛选
  filteredData.value = JSON.parse(JSON.stringify(fullWarningData.value));
  
  // 应用各筛选条件
  if (searchForm.goodsName) {
    const keyword = searchForm.goodsName.toLowerCase();
    filteredData.value = filteredData.value.filter(item => 
      item.goodsName.toLowerCase().includes(keyword) || 
      item.goodsCode.toLowerCase().includes(keyword)
    );
  }
  
  if (searchForm.goodsType) {
    filteredData.value = filteredData.value.filter(item => 
      item.goodsType === searchForm.goodsType
    );
  }
  
  if (searchForm.limitType) {
    filteredData.value = filteredData.value.filter(item => 
      item.warningType === searchForm.limitType
    );
  }
  
  if (searchForm.currentStockMin !== null && searchForm.currentStockMin !== undefined && searchForm.currentStockMin !== '') {
    filteredData.value = filteredData.value.filter(item => 
      item.currentStock >= searchForm.currentStockMin
    );
  }
  
  if (searchForm.currentStockMax !== null && searchForm.currentStockMax !== undefined && searchForm.currentStockMax !== '') {
    filteredData.value = filteredData.value.filter(item => 
      item.currentStock <= searchForm.currentStockMax
    );
  }
  
  // 更新分页数据
  updatePagedData();
};

// 查询逻辑（真实数据筛选）
const handleSearch = () => {
  console.log('库存预警查询条件：', searchForm);
  
  // 模拟查询延迟和加载状态
  const loading = ElLoading.service({
    lock: true,
    text: '正在查询预警数据...',
    spinner: 'el-icon-loading',
    background: 'rgba(0, 0, 0, 0.7)'
  });
  
  // 模拟查询延迟
  setTimeout(() => {
    applyFilters();
    loading.close();
    ElMessage.success(`查询成功，共${pagination.total}条预警记录`);
  }, 500);
};

// 重置逻辑
const handleReset = () => {
  searchForm.goodsName = '';
  searchForm.goodsType = '';
  searchForm.limitType = '';
  searchForm.currentStockMin = '';
  searchForm.currentStockMax = '';
  
  // 重新加载数据
  const loading = ElLoading.service({
    lock: true,
    text: '正在重置数据...',
    spinner: 'el-icon-loading',
    background: 'rgba(0, 0, 0, 0.7)'
  });
  
  setTimeout(() => {
    initData();
    loading.close();
    ElMessage.success('已重置查询条件');
  }, 300);
};

// 批量设置上下限
const handleBatchSetLimit = () => {
  console.log('批量设置上下限');
  ElMessage.info('批量设置上下限功能即将上线');
};

// 导出逻辑（模拟真实导出操作）
const handleExport = () => {
  console.log('导出库存预警数据');
  ElMessage.info('数据导出中，请稍候...');
  // 模拟导出延迟
  setTimeout(() => {
    ElMessage.success('数据导出成功！');
  }, 1000);
};

// 查看详情
const handleViewDetails = (row) => {
  console.log('查看详情：', row);
  currentData.value = row;
  detailDialogVisible.value = true;
};

// 刷新逻辑（模拟真实刷新操作）
const handleRefresh = () => {
  console.log('刷新库存预警页面');
  // 模拟刷新延迟和加载状态
  const loading = ElLoading.service({
    lock: true,
    text: '正在刷新预警数据...',
    spinner: 'el-icon-loading',
    background: 'rgba(0, 0, 0, 0.7)'
  });
  
  // 模拟刷新延迟
  setTimeout(() => {
    initData();
    // 如果有筛选条件，重新应用
    if (Object.values(searchForm).some(val => val)) {
      applyFilters();
    }
    loading.close();
    ElMessage.success('数据刷新成功！');
  }, 800);
};

// 分页逻辑（真实分页操作）
const handleSizeChange = (val) => {
  pagination.pageSize = val;
  console.log('库存预警每页条数变更：', val);
  // 更新分页数据
  updatePagedData();
  
  // 模拟加载状态
  const loading = ElLoading.service({
    lock: true,
    text: '正在加载数据...',
    spinner: 'el-icon-loading',
    background: 'rgba(0, 0, 0, 0.7)'
  });
  
  // 模拟加载延迟
  setTimeout(() => {
    loading.close();
  }, 300);
};

const handleCurrentChange = (val) => {
  pagination.currentPage = val;
  console.log('库存预警当前页码变更：', val);
  // 更新分页数据
  updatePagedData();
  
  // 模拟加载状态
  const loading = ElLoading.service({
    lock: true,
    text: '正在加载数据...',
    spinner: 'el-icon-loading',
    background: 'rgba(0, 0, 0, 0.7)'
  });
  
  // 模拟加载延迟
  setTimeout(() => {
    loading.close();
  }, 300);
};
</script>

<style scoped>
.stock-warning-page {
  padding: 16px;
  min-height: 100vh;
  background-color: #f5f7fa;
}

.page-title {
  font-size: 20px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 20px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 1px solid #ebeef5;
}

.table-title {
  font-size: 16px;
  font-weight: 500;
  color: #606266;
}

.data-count {
  font-size: 14px;
  color: #909399;
}

.stats-info {
  display: flex;
  align-items: center;
}

.mr-2 {
  margin-right: 8px;
}

.goods-name {
  color: #409EFF;
  cursor: pointer;
  display: block;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.goods-name:hover {
  text-decoration: underline;
}

.stock-below {
  color: #f56c6c;
  font-weight: 600;
}

.stock-above {
  color: #e6a23c;
  font-weight: 600;
}

.warning-row:hover {
  background-color: #f5f7fa;
}

.el-table {
  margin-bottom: 16px;
}

/* 自定义进度条样式 */
.el-progress-bar__outer {
  background-color: #f0f2f5;
  border-radius: 10px;
  overflow: hidden;
}

/* 详情页样式 */
.card-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 16px;
}

.section-title {
  font-size: 14px;
  font-weight: 500;
  color: #606266;
  margin-bottom: 12px;
}

.mt-4 {
  margin-top: 16px;
}

.text-green {
  color: #67c23a;
  font-weight: 500;
}

.text-red {
  color: #f56c6c;
  font-weight: 500;
}

.progress-large {
  height: 16px;
}

.trend-placeholder {
  text-align: center;
  color: #909399;
}

.trend-placeholder .el-icon--large {
  font-size: 48px;
  margin-bottom: 10px;
  color: #c0c4cc;
}

.recent-changes {
  margin-top: 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .el-form--inline .el-form-item {
    display: flex;
    flex-wrap: wrap;
    width: 100%;
  }
  
  .el-form-item__label {
    width: 100%;
    margin-right: 0;
    margin-bottom: 8px;
  }
  
  .flex {
    flex-direction: column;
  }
  
  .flex > * {
    margin-bottom: 10px;
  }
  
  .stats-info {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .mr-2 {
    margin-right: 0;
    margin-bottom: 5px;
  }
  
  /* 详情页响应式 */
  .el-descriptions {
    --el-descriptions-column: 1;
  }
  
  .trend-chart {
    height: 200px !important;
  }
}
</style>